package com.zbxj.wyz.controller;


import com.alibaba.fastjson.JSON;
import com.zbxj.wyz.domain.SystemUser;
import com.zbxj.wyz.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class LoginController {
    @Autowired
    LoginService loginService;

    @GetMapping("/")
    @ResponseBody
    public String home(){
        return "主页";
    }

    @PostMapping("/userLogin")
    @ResponseBody
    public ResponseEntity<String> login(@RequestBody SystemUser user) {
        ResponseEntity<String> responseEntity = loginService.login(user);
        return responseEntity;
    }

    @CacheEvict(cacheNames = "comment",allEntries = true)//清理comment中的缓存
    @GetMapping("/logout")
    @ResponseBody
    public ResponseEntity<String> logout(){
        ResponseEntity<String> responseEntity = loginService.logout();
        return responseEntity;
    }

    @PostMapping("/user/register")
    @ResponseBody
//    @PreAuthorize("hasAuthority('ROLE_administrators')")
    public String adduser(@RequestBody SystemUser user){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode1 = bCryptPasswordEncoder.encode(user.getPwd());
        user.setPwd(encode1);

        if (loginService.adduser(user)>0)
            return "success";
        else
            return "fail";
    }

    @GetMapping("/user/{name}")
    @ResponseBody
    public String getnameUser(@PathVariable("name") String name){
        String user= JSON.toJSONString(loginService.getnameUser(name));
        return user;

    }

}
